<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\member;

use app\common\model\MemberOfficialMenu;
use buwang\base\MemberBaseController;
use buwang\facade\WechatMp;

class Official extends MemberBaseController
{

    public function initialize()
    {
        parent::initialize();
        $this->model = new MemberOfficialMenu();
    }

    /**
     * 导航菜单
     */
    public function index(int $parent_id = 0)
    {
        //查询微信公众号或小程序是否存在
        if(!$this->member_miniapp_id) return $this->error_jump("未找到所属应用,请先开通应用");
        $miniapp = WechatMp::isTypes($this->member_miniapp_id);
        if (!$miniapp) return $this->error_jump('请先配置接入公众号',NOT_JUMP);
        /*if(!$miniapp){
            return redirect('system/passport.setting/pushAuth',['id' => $this->member_miniapp_id,'types'=>'mp']);
        }*/

        if (request()->isAjax()) {
            $page = request()->get('page/d', 1);
            $limit = request()->get('limit/d', 10);

            try {
                $total = MemberOfficialMenu::where(['member_miniapp_id' => $this->member_miniapp_id])->count();
                $list = MemberOfficialMenu::where(['member_miniapp_id' => $this->member_miniapp_id])->order('sort asc,id desc')->select()->toArray();

                //调用无限极分类重新排序
                $list && $list = infinite_get_son($list);

                $data = compact("total", 'list');
                return $this->success('successful', $data);
            } catch (\Exception $e) {
                return $this->error('查询失败', ['errorMsg' => $e->getMessage()]);
            }
        }

        $view['lists'] = MemberOfficialMenu::where(['member_miniapp_id' => $this->member_miniapp_id, 'parent_id' => $parent_id])->order('sort asc,id desc')->select();
        $view['menu'] = MemberOfficialMenu::where(['member_miniapp_id' => $this->member_miniapp_id])->order('sort asc,id desc')->select();
        $view['parent_id'] = $parent_id;
        $action_btn = $parent_id ? 5 : 3;
        $view['action_btn'] = count($view['lists']) >= $action_btn ? false : true;

        return view('', $view);
    }

    /**
     * 新增
     * @menu true
     */
    public function add()
    {
        if (request()->isPost()) {
            $param = request()->post();
            if ($param['parent_id'] == 0 && mb_strlen($param['name'], "utf-8") > 4) return $this->error('一级菜单最多4个汉字');
            if ($param['parent_id'] != 0 && mb_strlen($param['name'], "utf-8") > 7) return $this->error('二级菜单最多7个汉字');

            //菜单数量有限制
            $count = $this->model->where(['member_miniapp_id' => $this->member_miniapp_id, 'parent_id' => $param['parent_id']])->count();
            if ($param['parent_id'] == 0) {
                if ($count >= 3) return $this->error('一级菜单禁止超过3个');
            } else {
                if ($count >= 5) return $this->error('二级菜单禁止超过5个');
            }

            $this->model->startTrans();
            try {
                //TODO 新增记录
                $this->model->save($param);
                $this->model->commit();
            } catch (\Throwable $e) {
                $this->model->rollback();
                return $this->error('新增失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success();
        }

        $parents = MemberOfficialMenu::where(['member_miniapp_id' => $this->member_miniapp_id, 'parent_id' => 0])->order('sort asc,id desc')->select();
        $keys_where = [['keys', 'notin', ['subscribe', 'default']], ['status', '=', '1']];
        $keys = $this->app->db->name('WechatKeys')->where($keys_where)->order('sort desc,id desc')->select();
        return view('', compact('parents','keys'));
    }

    /**
     * 编辑
     * @menu true
     * @param int $id
     */
    public function edit($id = 0)
    {
        $row = $this->model->find($id);

        if (request()->isPost()) {
            if (!$row) return $this->error('记录不存在');

            $param = request()->post();
            //TODO 参数验证
            if ($param['parent_id'] == 0 && mb_strlen($param['name'], "utf-8") > 4) return $this->error('一级菜单最多4个汉字');
            if ($param['parent_id'] != 0 && mb_strlen($param['name'], "utf-8") > 7) return $this->error('二级菜单最多7个汉字');
            $this->model->startTrans();
            try {
                //TODO 更新记录
                $row->save($param);
                $this->model->commit();
            } catch (\Exception $e) {
                $this->model->rollback();
                return $this->error('编辑失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success('编辑成功');
        }

        if (!$row) return $this->error_jump('记录不存在');
        $parents = MemberOfficialMenu::where(['member_miniapp_id' => $this->member_miniapp_id, 'parent_id' => 0])->order('sort asc,id desc')->select();
        $keys_where = [['keys', 'notin', ['subscribe', 'default']], ['status', '=', '1']];
        $keys = $this->app->db->name('WechatKeys')->where($keys_where)->order('sort desc,id desc')->select();
        return view('', compact('row', 'parents','keys'));
    }

    /**
     * 删除
     * @menu true
     * @param int $ids 主键,删除多行时,拼接
     */
    public function del($ids = 0)
    {
        if (request()->isPost()) {
            if (!$ids) return $this->error('参数有误');

            $pk = $this->model->getPk();
            $list = $this->model->where($pk, 'in', $ids)->select();
            if (!$list) return $this->error('记录不存在');

            //有子菜单时无法删除
            $childrenCount = $this->model->where(['parent_id' => $ids])->find();
            if ($childrenCount) return $this->error('删除失败,请查看是否包含子菜单');

            $this->model->startTrans();
            try {
                foreach ($list as $item) {
                    $item->delete();
                }

                $this->model->commit();
            } catch (\Exception $e) {
                $this->model->rollback();
                return $this->error('删除失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success();
        }
    }

    /**
     * 公众号菜单排序
     * @access public
     */
    public function menuSort()
    {
        if (request()->isPost()) {
            $data = [
                'sort' => request()->post('sort/d'),
                'id' => request()->post('id/d'),
            ];

            //TODO 参数验证
            /*$validate = $this->validate($data,'Official.sort');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }*/

            $result = MemberOfficialMenu::where(['member_miniapp_id' => $this->member_miniapp_id, 'id' => $data['id']])->update(['sort' => $data['sort']]);
            if ($result) return $this->success();
            else return $this->error('操作失败');
        }
    }

    /**
     * 公众号菜单同步
     * @access public
     */
    public function sync()
    {
        if (request()->isPost()) {
            $menu = MemberOfficialMenu::official_menu($this->member_miniapp_id);

            if (empty($menu)) return $this->error('微信菜单没有创建');
            //验证公众号授权
            $official = WechatMp::isTypes($this->member_miniapp_id);
            if (!$official) return $this->error('【' . $this->member_miniapp->appname . '】微信认证失败,请确认公众号是否已经授权');
            $rel = $official->menu->create($menu);

            if ($rel['errcode'] == 0) return $this->success('【' . $this->member_miniapp->appname . '】同步成功');
            else return $this->error('【' . $this->member_miniapp->appname . '】同步失败,' . $rel['errmsg']);
        }
    }

    /**
     * 图文素材
     * @access public
     */
    public function materialList()
    {
        if (request()->isAjax()) {
            $page = request()->get('page/d', 1);
            $limit = request()->get('limit/d', 10);
            $type = request()->get('type/s', 'news');
            try {
                $offset = $page - 1;
                $this->isMemberAppAuth();//保证有初始值
                $app = WechatMp::isTypes($this->member_miniapp_id);
                $res = $app->material->list($type, $offset, $limit);
                //var_dump($res);die;
            } catch (\Exception $e) {
                return $this->error('查询失败', ['errorMsg' => $e->getMessage()]);
            }
            $result = [];
            $total_count = $res['total_count'];
            switch ($type) {
                case 'news':
                    foreach ($res['item'] as $k => $v) {
                        //var_dump($v['content']['news_item'][0]['thumb_url']);die;
                        $result[$k]['media_id'] = $v['media_id'];
                        $result[$k]['thumb_url'] = $v['content']['news_item'][0]['thumb_url'];
                        $result[$k]['title'] = $v['content']['news_item'][0]['title'];
                    }
                    break;
                case 'image':
                    foreach ($res['item'] as $k => $v) {
                        $result[$k]['media_id'] = $v['media_id'];
                        $result[$k]['thumb_url'] = $v['url'];
                        $result[$k]['title'] = $v['name'];
                    }
                    break;
                case 'video':
                    foreach ($res['item'] as $k => $v) {
                        $result[$k]['media_id'] = $v['media_id'];
                        $result[$k]['thumb_url'] = $v['cover_url'];
                        $result[$k]['title'] = $v['name'];
                    }
                    break;
                default:
                    foreach ($res['item'] as $k => $v) {
                        $result[$k]['media_id'] = $v['media_id'];
                        $result[$k]['thumb_url'] = '';
                        $result[$k]['title'] = $v['name'];
                    }
                    break;
            }
            $data = [
                'code' => 0,
                'msg' => 'success',
                'count' => $total_count,
                'data' => $result,
            ];
            return json($data);
        }
    }

}
